package src

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"lutai/src/logger"
	"lutai/src/service/db"

	"github.com/teambition/gear"
	"github.com/teambition/gear/logging"
	"github.com/teambition/gear/middleware/static"
)

// Version 版本号
const Version = "v1.0.0-alpha.1"

// Config 配置参数
type Config struct {
	StaticPath string
	DBConfig   *db.Config
}

// New 创建APP实例
func New(cfg *Config) (*gear.App, *db.DB) {
	logger.Infof("服务正在初始化，当前版本：%s", Version)

	app := gear.New()
	db, err := db.NewDB(cfg.DBConfig)
	if err != nil {
		logger.Fatalf("初始化DB发生错误:%s", err.Error())
	}

	if spath := cfg.StaticPath; spath != "" {
		staticMiddleware := static.New(static.Options{
			Root:   spath,
			Prefix: "/",
		})
		app.Use(func(ctx *gear.Context) (err error) {
			if strings.HasPrefix(ctx.Path, "/api") {
				return
			}

			_, verr := os.Stat(filepath.Join(spath, ctx.Path))
			if verr != nil && os.IsNotExist(verr) {
				http.ServeFile(ctx.Res, ctx.Req, filepath.Join(spath, "index.html"))
				return
			}

			err = staticMiddleware(ctx)
			return
		})
	}

	app.UseHandler(logging.Default(app.Env() == "development"))
	app.UseHandler(newRouter(db))

	return app, db
}
